import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { Action, ElMessageBox } from 'element-plus';
import NProgress from 'nprogress';
import { OVERTIME_CODE, TOKEN } from '../constant/index';
import { getItem, sessionSetItem } from './storage';

// 设置请求头和请求路径
//@ts-ignore
axios.defaults.baseURL = import.meta.env.VITE_APP_BASE_API
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.interceptors.request.use(
  (config): AxiosRequestConfig<any> => {
    const token = getItem(TOKEN)
    if (token) {
      //@ts-ignore
      config.headers.token = token
    }
    return config
  },
  (error) => {
    return error
  }
)
// 响应拦截
axios.interceptors.response.use((res:AxiosResponse) => {
  // token过期操作
  if (res.data.status === OVERTIME_CODE) {
    handleTokenFailure()
  }
  return res
})

interface Request {
  get<T>(url: string, params?: unknown): Promise<AxiosResponse<T>>
  post<T>(url: string, params?: unknown): Promise<AxiosResponse<T>>
  upload<T>(url: string, params: unknown): Promise<AxiosResponse<T>>
  download(url: string): void
}

const Request: Request = {
  get(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .get(url, { params })
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  post(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .post(url, JSON.stringify(params))
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  upload(url, file) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .post(url, file, {
          headers: { 'Content-Type': 'multipart/form-data' },
        })
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  download(url) {
    const iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    iframe.src = url
    iframe.onload = function () {
      document.body.removeChild(iframe)
    }
    document.body.appendChild(iframe)
  },
}
const handleTokenFailure = () => {
  sessionSetItem('token', '')
  const message = "登录超时，是否返回登录页？"
  // 提示登录过期，然后去登录页
  const loginUrl = getItem('fromLoginSourceURL')
  ElMessageBox.alert(message, '系统提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type:'error',
    callback: (action: Action) => {
      if(action==='confirm') {
        window.location.href = loginUrl || "/login/index.html";
      } else {
        window.close();
      }
    }
  })
}
export default Request;